package com.topsec.manager.util;

import com.luciad.imageio.webp.WebPReadParam;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 处理图片
 *
 * @author hyq
 * @email 22261392@qq.com
 * @date 2019-04-08 13:34:28
 *
 */
public class ImageUtil {

	/**
	 * 处理 webp 格式图像为常规图像
	 *
	 * @param sourceFile
	 *            来源全路径 /xxx/xx/dd.png
	 * @param targetFile
	 *            目的全路径 /sss/ss/dd.png
	 */
	public static void dealImageType(String sourceFile, String targetFile) {

		FileImageInputStream input = null;
		try {
			boolean tag = false;
			String ext = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
			if (ext.toLowerCase().equals("jpeg")) {
				tag = true;
			} else if (ext.toLowerCase().equals("png")) {
				tag = true;
			} else if (ext.toLowerCase().equals("jpg")) {
				tag = true;
			} else if (ext.toLowerCase().equals("gif")) {
				tag = true;
			}

			if (tag) {
				input = new FileImageInputStream(new File(sourceFile));
				String type = getImageType(input);
				if ("webp".equals(type)) { // 解码webp为常规格式图片数据
					System.out.println(" ===>>> 当前要转换格式的图片地址为：" + sourceFile);
					// 获取实例
					ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
					// 配置解码器
					WebPReadParam readParam = new WebPReadParam();
					readParam.setBypassFiltering(true);
					// 读取文件
					reader.setInput(input);
					// 解码图像
					BufferedImage image = reader.read(0, readParam);
					ImageIO.write(image, ext, new File(sourceFile));
					// 关闭
					reader.dispose();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 判断图片的隐藏格式
	 */
	public static String getImageType(FileImageInputStream inputStream) throws Exception {

		byte[] bs = new byte[4];
		inputStream.read(bs, 0, bs.length);
		String type = toHexString(bs).toUpperCase(); // 将字母转换为大写
		if (type.contains("FFD8FF")) {
			return "jpg";
		} else if (type.contains("89504E47")) {
			return "png";
		} else if (type.contains("47494638")) {
			return "gif";
		} else if (type.contains("424D")) {
			return "bmp";
		} else if (type.contains("RIFF")) {
			return "webp";
		} else {
			return "unknown";
		}
	}

	/**
	 * 将 byte 数据转换成 16 进制
	 */
	public static String toHexString(byte[] bytes) {
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append(new String(bytes));
		return sBuilder.toString();
	}
}
